package com.example.tuike.controller;

import com.example.tuike.common.utils.JwtUtils;
import com.example.tuike.dto.UserDto;
import com.example.tuike.entity.User;
import com.example.tuike.service.UserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/*** @Author supersaiya
 * @Description TODO

 * @Date 2025/1/29 16:59

 * @Version 1.0*/
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;
    private static final Logger log = LoggerFactory.getLogger(UserService.class);

    @PostMapping("/login")
    public ResponseEntity<Map<String, String>> login(@RequestBody UserDto userdto) {
        // 从数据库中获取用户信息
        User storedUser = userService.getUserByUsername(userdto.getUsername());
        if (storedUser == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "用户名或密码错误"));
        }
        log.warn("用户名是 "  + storedUser.getUsername() + "密码是" + storedUser.getPasswordHash());

        // 验证密码
        if (!passwordEncoder.matches(userdto.getPassword(), storedUser.getPasswordHash())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "用户名或密码错误"));
        }
        log.warn("验证成功");
        // 验证凭证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(userdto.getUsername(), userdto.getPassword())
        );

        // 生成 Token
        String token = jwtUtils.generateToken(authentication.getName());

        // 将认证信息存入上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);

        return ResponseEntity.ok(Map.of("token", token));
    }
    @GetMapping("/me")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token");
            }
            String jwt = token.substring(7); // 去掉 "Bearer " 前缀
            String username = jwtUtils.extractUsername(jwt);
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户不存在");
            }
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token");
        }
    }
}